package com.aptemo.webetek.client.utils;

public class TokenUtils
{

	public static String setToken(String token, String name, String value)
	{

		// check if token contains
		if (token.contains(name))
		{
			String part = getTokenPart(token, name);

			String result = part;
			String[] pair = part.split("-", 2);
			if (pair.length < 2)
			{
				// token = token + value;
			}
			else
			{
				if (pair[1].isEmpty())
				{
					result += value;
				}
				else
				{
					result = part.replace(pair[1], value);
					// append rest...
					// token += pair[2];
				}
			}
			token = token.replace(part, result);

		}
		else
		{
			int ind = token.indexOf("/p");

			String fst = token;
			if (ind >= 0)
			{
				fst = token.substring(0, ind);
			}
			fst += "/" + name + "-" + value;
			if (ind >= 0)
			{
				fst += token.substring(ind);
			}
			token = fst;
		}

		return token;
	}

	public static String getTokenPart(String token, String name)
	{
		String[] tokens = token.split("/");
		for (int i = 0; i < tokens.length; i++)
		{
			String filterName = tokens[i].split("-")[0];
			if (filterName.equals(name))
			{
				return tokens[i];
			}
		}
		return "";
	}

	public static String getTokenValue(String token, String name)
	{
		String input = getTokenPart(token, name);
		String[] tokens = input.split("-");
		if (tokens.length == 2)
		{
			return tokens[1];
		}
		return "";
	}

	public static String removeToken(String token, String name)
	{
		if (token.contains(name))
		{
			String tail = token.substring(token.indexOf(name));

			int end = tail.indexOf("/");

			if (end >= 0)
			{
				String tk = tail.substring(0, end + 1);
				token = token.replace("/" + tk, "");
			}
			else
			{
				token = token.replace("/" + tail, "");
			}

		}
		return token;
	}
}
